from rest_framework import serializers

from article.models import Article
from my.models import User


# 获取文章列表
class ArticleSerializer(serializers.ModelSerializer):
    cate_name = serializers.SerializerMethodField()

    class Meta:
        model = Article
        fields = ['id', 'title', 'content', 'cover_img', 'pub_date', 'state', 'cate_id', 'user_id', 'cate_name']

    def get_cate_name(self, obj):
        return obj.cate_id.cate_name if obj.cate_id else '待分类'

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'email', 'nickname']

# 获取文章详情
class DetailArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title', 'content', 'cover_img', 'pub_date', 'state', 'cate_id', 'user_id']

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if instance.user_id:
            user_data = UserSerializer(instance.user_id).data
            data.update(user_data)
        return data

